package com.sqx.modules.app.controller.app;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.annotation.LoginUser;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.AppService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.riderLine.entity.RiderLine;
import com.sqx.modules.riderLine.service.RiderLineService;
import com.sqx.modules.timedtask.service.RiderLocationService;
import com.sqx.modules.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app/user")
@Api(value = "APP管理", tags = {"APP管理"})
public class AppController {

    @Autowired
    private UserService userService;
    @Autowired
    private AppService appService;
    @Autowired
    private RiderLineService lineService;
    @Autowired
    private RiderLocationService riderLocationService;

    @Login
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端修改密码")
    public Result updatePwd(@LoginUser UserEntity user, String pwd, String oldPwd) {
        if (!user.getPassword().equals(DigestUtils.sha256Hex(oldPwd))) {
            return Result.error("原始密码不正确！");
        }
        if (pwd.equals(oldPwd)) {
            return Result.error("新密码不能与旧密码相同！");
        }
        user.setPassword(DigestUtils.sha256Hex(pwd));
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
    @ApiOperation("用户端换绑手机号")
    @ResponseBody
    public Result updatePhone(@RequestAttribute("userId") Long userId, @RequestParam String phone, @RequestParam String msg) {
        return userService.updatePhone(phone, msg, userId);
    }

    @Login
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ApiOperation("用户修改个人信息")
    @ResponseBody
    public Result updateUser(@RequestBody UserEntity userEntity, @RequestAttribute("userId") Long userId) {
        UserEntity entity = userService.getById(userId);
        if (entity.getOnLineFlag() != null && entity.getOnLineFlag() == 2 && userEntity.getOnLineFlag() != null && userEntity.getOnLineFlag() == 1) {
            if (!"1".equals(entity.getCheckCertification())) {
                return Result.error("请在实名认证通过后再进行上线");
            }
        }
        userEntity.setUserId(userId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateLine", method = RequestMethod.POST)
    @ApiOperation("师傅上下线")
    @ResponseBody
    public Result updateLine(@RequestAttribute("userId") Long userId) {
        UserEntity entity = userService.getById(userId);
        //上线
        if (entity.getOnLineFlag() != null && entity.getOnLineFlag() == 2) {
            if (!"1".equals(entity.getCheckCertification())) {
                return Result.error("请在实名认证通过后再进行上线");
            } else {
                RiderLine riderLine = new RiderLine();
                riderLine.setUserId(userId);
                riderLine.setStartTime(LocalDateTime.now());
                riderLine.setLineDuration(0);
                lineService.save(riderLine);
                entity.setOnLineFlag(1);
            }
            //下线
        } else {
            RiderLine riderLine = lineService.getNowOneLine(userId);
            if (riderLine == null) {
                riderLine = new RiderLine();
                riderLine.setUserId(userId);
                riderLine.setStartTime(LocalDate.now().atTime(0, 0, 0));
                riderLine.setEndTime(LocalDateTime.now());
                Duration duration = Duration.between(riderLine.getStartTime(), riderLine.getEndTime());
                long minutes = duration.toMinutes();
                riderLine.setLineDuration((int) minutes);
                lineService.save(riderLine);
            } else {
                riderLine.setEndTime(LocalDateTime.now());
                Duration duration = Duration.between(riderLine.getStartTime(), riderLine.getEndTime());
                long minutes = duration.toMinutes();
                riderLine.setLineDuration(riderLine.getLineDuration() + (int) minutes);
                lineService.updateById(riderLine);
            }
            entity.setOnLineFlag(2);
        }

        userService.updateById(entity);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserImageUrl", method = RequestMethod.POST)
    @ApiOperation("用户修改头像")
    @ResponseBody
    public Result updateUserImageUrl(@LoginUser UserEntity user, String avatar) {
        user.setAvatar(avatar);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserName", method = RequestMethod.POST)
    @ApiOperation("用户修改昵称")
    @ResponseBody
    public Result updateUserName(@LoginUser UserEntity user, String userName) {
        user.setNickName(userName);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/selectUserById", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@LoginUser UserEntity user) {
        return Result.success().put("data", user);
    }


    @RequestMapping(value = "/selectNewApp", method = RequestMethod.GET)
    @ApiOperation("升级检测")
    @ResponseBody
    public Result selectNewApp() {
        return Result.success().put("data", appService.selectNewApp());
    }

    @RequestMapping(value = "/updateClientId", method = RequestMethod.GET)
    @ApiOperation("绑定ClientId")
    @ResponseBody
    public Result updateClientId(String clientId, Long userId, Integer sysPhone) {
        UserEntity userEntity = new UserEntity();
        userEntity.setSysPhone(sysPhone);
        userEntity.setUserId(userId);
        userEntity.setClientid(clientId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @RequestMapping(value = "/updateClientRiderId", method = RequestMethod.GET)
    @ApiOperation("绑定师傅ClientId")
    @ResponseBody
    public Result updateClientRiderId(String clientRiderId, Long userId, Integer sysPhone) {
        UserEntity userEntity = new UserEntity();
        userEntity.setSysPhone(sysPhone);
        userEntity.setUserId(userId);
        userEntity.setClientRiderId(clientRiderId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @Login
    @GetMapping("/queryInviterCount")
    public Result select(@LoginUser UserEntity userEntity) {
        int count = userService.queryInviterCount(userEntity.getInvitationCode());
        return Result.success().put("data", count);
    }

    /**
     * (师傅端)获取附近司机
     * @return
     */
    @Login
    @GetMapping("getRiderCount")
    public Result getRiderCount(@RequestAttribute("userId") Long userId, String city, Double lng, Double lat) {
        return Result.success().put("data", riderLocationService.getRiderCount(userId, city, lng, lat));
    }
}
